package com.gxa.interceptor;

import com.gxa.exception.NoAjaxException;
import com.gxa.exception.SystemException;
import com.gxa.pojo.Auth;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean isSuper = (Boolean) request.getSession().getAttribute("isSuper");
        if(isSuper){
            return true;
        }
        List<Auth> authList = (List<Auth>) request.getSession().getAttribute("authList");
        String servletPath = request.getServletPath();
        for (Auth auth : authList) {
            if (auth.getAuthUrl() == null) {
                continue;
            }
            if(auth.getAuthUrl().equals(servletPath)){
                return true;
            }
        }
        if(isAjax(request)){
            throw new SystemException(1005, "对不起，你不配！");
        }
        throw new NoAjaxException(1006, "对不起，你不配！");

    }

    private Boolean isAjax(HttpServletRequest request){
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equals("XMLHttpRequest")){
           return true;
        }
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
